package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.annotation.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.enumeration.OperationType;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl  extends ServiceImpl<EmployeeMapper,Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = baseMapper.getByUsername( username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }
    @AutoFill(value = OperationType.INSERT)
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        // 使用BeanUtils拷贝属性（注意：属性名要一致）
        BeanUtils.copyProperties(employeeDTO, employee);

        // 设置其他必要属性（如状态、创建时间等）
        employee.setStatus(StatusConstant.ENABLE); // 默认启用
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        // 设置默认密码（需加密）
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        // 设置创建人和修改人的id
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());
        // 使用MyBatis Plus的insert方法
        employeeMapper.insert(employee);
    }

    @Override
    public Page<Employee> page(EmployeePageQueryDTO employeePageQueryDTO) {
       return baseMapper.selectPage(
               new Page<>(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize()),
               new LambdaQueryWrapper<Employee>()
                       .like(StringUtils.isNotBlank(employeePageQueryDTO.getName()),Employee::getName, employeePageQueryDTO.getName())
                       .orderByDesc(Employee::getCreateTime)
       )    ;

    }

    /**
     * 启用禁用员工账号
     */
    @AutoFill(value = OperationType.UPDATE)
    @Override
    public void startOrStop(Integer status, Long id) {
        Employee employee = new Employee();
        employee.setId( id);
        employee.setStatus(status);
        employee.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(employee);
    }

    /**
     * 编辑员工信息
     */
    @AutoFill(value = OperationType.UPDATE)
    @Override
    public void updateEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(employee);
    }


}
